<!--
 * @Author: your name
 * @Date: 2021-08-04 14:08:32
 * @LastEditTime: 2021-09-27 17:26:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \usp-osm-frondend\src\views\couponsCenter\couponMgmt\detail.vue
-->
<template>
  <div v-loading="pageLoading" element-loading-text="加载中">
    <div class="newPageTitle">
      <span class="backIcon" @click="goBack"><i class="el-icon-back"></i></span>
      <h1 style="display: inline-block; margin-left: 10px; font-weight: bold">
        <span v-if="type === 'add'">新建</span>
        <span v-else-if="type === 'edit'">编辑</span>
        <span v-else-if="type === 'detail'">详情</span>
      </h1>
    </div>
    <div class="content">
      <div class="detail-content-section">
        <h2>基本信息</h2>
        <el-row>
          <el-col :span="12" :offset="1">
            <el-form
              :model="couponForm"
              :rules="couponFormRules"
              ref="couponForm"
              label-width="140px"
            >
              <el-form-item label="券池编号：" v-if="!isAdd">
                <el-input disabled v-model="couponForm.couponCode"></el-input>
              </el-form-item>
              <el-form-item label="券池来源：" prop="source">
                <el-select :disabled="!isAdd" @change="selectSource" v-model="couponForm.source" placeholder="请选择">
                  <el-option
                    v-for="item in lookupItems.SOURCEOFCOUPONPOOL"
                    :key="item.id"
                    :label="item.dicName"
                    :value="item.dicCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="券池名称：" prop="couponName">
                <el-input
                  :disabled="status === '3' || status === '2'"
                  v-model="couponForm.couponName"
                  @input="couponForm.couponName = couponForm.couponName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
                  maxlength="10"
                  show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item label="核销方：" prop="consumer">
                <el-select :disabled="status === '3' || status === '2'" v-model="couponForm.consumer" placeholder="请选择">
                  <el-option
                    v-for="item in lookupItems.COUPONPOOLCONSUMER"
                    :key="item.id"
                    :label="item.dicName"
                    :value="item.dicCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发券方式：" prop="distributionMethod">
                <el-select
                  :disabled="couponForm.source === '1' || status === '3' || status === '2'"
                  v-model="couponForm.distributionMethod"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in lookupItems.DISTRIBUTIONMETHOD"
                    :key="item.id"
                    :label="item.dicName"
                    :value="item.dicCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div class="detail-content-section">
        <h2>详细信息</h2>
        <el-row>
          <el-col :span="12" :offset="1">
            <el-form
              :model="detailForm"
              :rules="detailFormRules"
              ref="detailForm"
              label-width="140px"
            >
              <el-form-item label="业务类型：" prop="businessType">
                <el-select
                  :disabled="status === '3' || status === '2'"
                  v-model="detailForm.businessType"
                  placeholder="请选择..."
                >
                  <el-option
                    v-for="item in lookupItems.BUSINESSTYPE"
                    :key="item.id"
                    :label="item.dicName"
                    :value="item.dicCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="面值：" prop="faceValue">
                <el-input
                  :disabled="status === '3' || status === '2'"
                  type="number"
                  placeholder=""
                  v-model="detailForm.faceValue"
                  @input="detailForm.faceValue = detailForm.faceValue.replace(/\D/g,'')"
                ></el-input>
              </el-form-item>
              <el-form-item label="投放数量：" v-if="couponForm.source === '1' || couponForm.source === ''">
                <el-input
                  :disabled="status === '3' || status === '2'"
                  type="number"
                  placeholder="不填时为无限数量"
                  v-model="detailForm.launchQuantity"
                  @input="detailForm.launchQuantity =detailForm.launchQuantity.replace(/\D/g, '')"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="券码前缀："
                prop="couponPrefix"
                v-if="couponForm.source === '1' || couponForm.source === ''"
              >
                <el-input
                  :disabled="status === '3' || status === '2'"
                  placeholder="格式为四个英文字母大写"
                  maxlength="4"
                  v-model="detailForm.couponPrefix"
                  @input="detailForm.couponPrefix = detailForm.couponPrefix.replace(/[^\A-\Z]/g,'')"
                ></el-input>
              </el-form-item>
              <el-form-item label="发放有效期：">
                <div class="block">
                  <el-date-picker
                    :disabled="status === '3' || status === '2'"
                    v-model="detailForm.grantExpiryDate"
                    type="daterange"
                    range-separator="至"
                    :default-value="[new Date(), new Date()]"
                    value-format="yyyy-MM-dd"
                    start-placeholder="起"
                    end-placeholder="止"
                  ></el-date-picker>
                </div>
              </el-form-item>
              <el-form-item
                label="使用有效期类型："
                prop="periodType"
                v-if="couponForm.source === '1' || couponForm.source === ''"
              >
                <el-select :disabled="status === '3' || status === '2'" v-model="detailForm.periodType" placeholder="">
                  <el-option
                    v-for="item in lookupItems.PERIODTYPE"
                    :key="item.id"
                    :label="item.dicName"
                    :value="item.dicCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="使用有效期："
                prop="usePeriodDate"
                v-if="couponForm.source !== '2' && detailForm.periodType !== '2'"
              >
                <div class="block">
                  <el-date-picker
                    :disabled="status === '3' || status === '2'"
                    v-model="detailForm.usePeriodDate"
                    type="daterange"
                    range-separator="至"
                    :default-value="[new Date(), new Date()]"
                    value-format="yyyy-MM-dd"
                    start-placeholder="起"
                    end-placeholder="止"
                    :picker-options="pickerOptions"
                  ></el-date-picker>
                </div>
              </el-form-item>
              <el-form-item
                prop="periodDay"
                class="formPosition"
                label="有效期天数"
                v-if="detailForm.periodType !== '1' && couponForm.source !== '2'"
              >
                <el-input :disabled="status === '3' || status === '2'" type="number" v-model="detailForm.periodDay" placeholder="有效期天数"></el-input>
              </el-form-item>
              <el-form-item label="服务商：" prop="serviceProvidersName">
                <el-autocomplete
                  style="width: 100%"
                  :disabled="status === '3' || status === '2'"
                  v-model="detailForm.serviceProvidersName"
                  value-key="name"
                  :debounce="500"
                  :fetch-suggestions="querySearchAsync"
                  placeholder="请根据供应商CODE/进行选择"
                  @select="handleSelect"
                ></el-autocomplete>
              </el-form-item>
              <el-form-item label="券图标：">
                <el-upload
                  :disabled="status === '3'"
                  :class="{ hideUpload: isUpload }"
                  :action="uploadUrl"
                  :headers="myHeaders"
                  :data="uploadData"
                  :file-list="fileList"
                  :on-success="onSuccess"
                  :on-error="onError"
                  :limit="1"
                  :on-change="onChange"
                  list-type="picture-card"
                  :on-remove="handleRemove"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="券文描：">
                <el-input
                  :disabled="status === '3'"
                  style="border-radius: 15px"
                  type="textarea"
                  rows="3"
                  v-model="detailForm.description"
                  placeholder="请输入"
                  maxlength="100"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <div style="margin-top: 20px; text-align: right">
          <el-button v-if="status !== '3'" class="search-btn" @click="onClear">清空</el-button>
          <el-button v-if="status !== '3'" class="search-btn" @click="onSave">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getServiceProviderList } from '@/api/service'
import Vue from 'vue'
import { setRouterParams, getRouterParams } from '@/utils/auth'
import { ACCESS_TOKEN } from '@/config/variableInit'
import { common } from '@/mixins/common'
import { mapGetters } from 'vuex'
// import { cloneDeep } from 'lodash'
import { getCouponDetail, saveCoupon } from '@/api/coupon'
import { timestampToChange } from '@/filters'
export default {
  name: 'couponDetail',
  data () {
    return {
      inputData: [],
      id: '',
      isAdd: true,
      queryDatas: [],
      selectData: '',
      couponForm: {
        couponCode: '',
        source: '',
        couponName: '',
        consumer: '',
        distributionMethod: ''
      },
      couponFormRules: {
        source: [
          { required: true, message: '请选择券池来源', trigger: 'change' }
        ],
        couponName: [
          { required: true, message: '请输入券池名称', trigger: 'blur' }
        ],
        consumer: [
          { required: true, message: '请选择核销方', trigger: 'change' }
        ],
        distributionMethod: [
          { required: true, message: '请选择发券方式', trigger: 'change' }
        ]
      },
      type: '',
      addSave: false,
      detailForm: {
        businessType: '',
        faceValue: '',
        couponPrefix: '',
        periodType: '',
        serviceProvidersName: '',
        serviceProvidersCode: '',
        launchQuantity: '',
        description: '',
        grantExpiryDate: '',
        periodDay: '',
        usePeriodDate: '',
        iconUrl: ''
      },
      detailFormRules: {
        businessType: [
          { required: true, message: '请选择业务类型', trigger: 'change' }
        ],
        faceValue: [{ required: true, message: '请输入面值', trigger: 'blur' }],
        couponPrefix: [
          { required: true, message: '请券码前缀', trigger: 'blur' },
          { min: 4, max: 4, message: '长度在4个大写英文字母', trigger: 'blur' }
        ],
        periodType: [
          { required: true, message: '请选择使用有效期类型', trigger: 'change' }
        ],
        serviceProvidersName: [
          { required: true, message: `${this.addSave ? '' : '服务商不能为空'}`, trigger: ['blur', 'change'] }
        ],
        usePeriodDate: [
          { required: true, message: '请选择使用有效期', trigger: ['blur', 'change'] }
        ],
        periodDay: [
          { required: true, message: '请选择使用有效天数', trigger: 'blur' }
        ]
      },
      status: '',
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_URL + '/admin/upload/uploadFile',
      myHeaders: { Authorization: Vue.ls.get(ACCESS_TOKEN) },
      uploadData: { fileFlag: 'CATEGORY' },
      isUpload: false,
      pageLoading: false,
      pickerOptions: {
        // disabledDate (time) {
        //   if (this.grantExpiryDate.length !== 0) {
        //     console.log(this.grantExpiryDate[0])
        //   }
        //   // 如果没有后面的-8.64e7就是不可以选择今天的
        //   return time.getTime() > Date.now() // - 8.64e7
        // }
        disabledDate: this.disabledDate
      }
    }
  },
  mixins: [common],
  computed: {
    ...mapGetters(['lookupItems'])
  },
  watch: {
    queryDatas: {
      handler (val) {
        if (val.length === 0) {
          this.addSave = true
        } else {
          this.addSave = false
        }
      },
      deep: true
    }
  },
  mounted () {
    this.loadAll()
    // const params = {}
    const name = this.$route.name
    this.type = this.$route.params.type
    this.status = this.$route.params.status
    if (this.type === 'detail') {
      this.$route.meta.title = '券池详情'
      this.$route.meta.titlePath = '券池详情'
    } else if (this.type === 'edit') {
      this.$route.meta.title = '编辑'
      this.$route.meta.titlePath = '编辑'
    } else if (this.type === 'add') {
      this.$route.meta.title = '新增'
      this.$route.meta.titlePath = '新增'
    }
    if (this.$route.params.id) {
      this.id = this.$route.params.id
      this.isAdd = false
      setRouterParams(this.$route)
      this.getDetails(this.id)
    } else {
      if (name === 'couponDetail') {
        this.isAdd = false
        const routeParams = getRouterParams(this.$route)
        this.type = routeParams.type
        this.id = routeParams.id
        this.status = routeParams.status
        this.getDetails(this.id)
      } else {
        this.isAdd = true
        this.type = 'add'
        this.initData()
      }
    }
    // if (this.$route.params.id) {
    //   setRouterParams(this.$route)
    //   params = this.$route.params
    // } else {
    //   params = getRouterParams(this.$route)
    // }
    // if (name === 'couponDetail') {
    //   this.isAdd = false
    //   this.id = params.id
    //   this.type = params.type
    //   this.status = params.status
    //   this.getDetails(this.id)
    // } else {
    //   this.isAdd = true
    //   this.initData()
    // }
  },
  methods: {
    disabledDate (time) {
      const grantExpiryDate = this.detailForm.grantExpiryDate
      if (grantExpiryDate.length !== 0) {
        return time.getTime() < new Date(grantExpiryDate[0] + ' ' + '00:00:00').getTime()
      } else {
        return false
      }
    },
    initData () {
      this.detailForm = {
        businessType: '',
        faceValue: '',
        couponPrefix: '',
        periodType: '1',
        serviceProvidersName: '',
        serviceProvidersCode: '',
        launchQuantity: '',
        description: '',
        grantExpiryDate: '',
        periodDay: '',
        usePeriodDate: '',
        iconUrl: ''
      }
      this.couponForm = {
        couponCode: '',
        source: '',
        couponName: '',
        consumer: '',
        distributionMethod: ''
      }
    },
    selectSource (val) {
      if (val === '1') {
        this.couponForm.distributionMethod = '1'
        this.couponForm.couponName = ''
        this.couponForm.consumer = ''
        this.detailForm = {
          businessType: '',
          faceValue: '',
          couponPrefix: '',
          periodType: '1',
          serviceProvidersName: '',
          launchQuantity: '',
          description: '',
          grantExpiryDate: '',
          periodDay: '',
          usePeriodDate: '',
          iconUrl: ''
        }
      } else {
        this.couponForm.distributionMethod = ''
        this.couponForm.couponCode = ''
        this.couponForm.couponName = ''
        this.couponForm.consumer = ''
        this.detailForm = {
          businessType: '',
          faceValue: '',
          couponPrefix: '',
          periodType: '1',
          serviceProvidersName: '',
          launchQuantity: '',
          description: '',
          grantExpiryDate: '',
          periodDay: '',
          usePeriodDate: '',
          iconUrl: ''
        }
      }
    },
    getDetails (id) {
      const params = {
        id: id
      }
      this.pageLoading = true
      getCouponDetail(params).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            const allData = res.obj
            this.setData(allData)
            // this.fileList.push({ url: res.obj.iconUrl })
            if (res.obj.iconUrl) {
              this.isUpload = true
              this.fileList.push({ url: res.obj.iconUrl })
            }
          } else {
            this.$alert('获取券池详情失败')
          }
          this.pageLoading = false
        }
      })
    },
    setData (datas) {
      this.couponForm = {
        couponCode: datas.couponCode,
        source: datas.source,
        couponName: datas.couponName,
        consumer: datas.consumer,
        distributionMethod: datas.distributionMethod
      }
      this.detailForm = {
        businessType: datas.businessType,
        faceValue: datas.faceValue,
        couponPrefix: datas.couponPrefix,
        periodType: datas.periodType,
        serviceProvidersName: datas.serviceProvidersName,
        serviceProvidersCode: datas.serviceProvidersCode,
        launchQuantity: datas.launchQuantity,
        description: datas.description,
        grantExpiryDate: [timestampToChange(datas.beginGrantExpiry, 'date'), timestampToChange(datas.endGrantExpiry, 'date')],
        periodDay: datas.periodDay,
        usePeriodDate: [timestampToChange(datas.beginUsePeriod, 'date'), timestampToChange(datas.endUsePeriod, 'date')],
        iconUrl: datas.iconUrl
      }
    },
    loadAll () {
      const params = {
        code: '',
        contactAddress: '',
        contactEmail: '',
        contactPhone: '',
        contactUser: '',
        name: '',
        status: '1',
        type: ''
      }
      getServiceProviderList(params).then((response) => {
        const data = response
        if (Number(data.code) === 1) {
          this.inputData = data.obj
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    querySearchAsync (queryString, cb) {
      const results = queryString
        ? this.inputData.filter(this.createStateFilter(queryString))
        : this.inputData
      this.queryDatas = results
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 3000 * Math.random())
    },
    createStateFilter (queryString) {
      return (state) => {
        return (
          state.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0 || state.code.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    handleSelect (item) {
      this.selectData = item
    },
    onSave () {
      const rulesOne = new Promise((resolve, reject) => {
        this.$refs.couponForm.validate(valid => {
          if (valid) {
            resolve()
          } else {
            return false
          }
        })
      })

      const rulesTwo = new Promise((resolve, reject) => {
        this.$refs.detailForm.validate(valid => {
          if (valid) {
            resolve()
          } else {
            return false
          }
        })
      })
      if (this.couponForm.source === '2') {
        this.detailForm.periodType = ''
      }
      if (this.detailForm.launchQuantity === '') {
        this.detailForm.launchQuantity = null
      }
      if (this.detailForm.serviceProvidersName) {
        this.detailForm.serviceProvidersCode = this.selectData.code
      }
      const params = {
        id: this.id,
        ...this.couponForm,
        ...this.detailForm,
        beginUsePeriod: this.detailForm.usePeriodDate ? new Date(this.detailForm.usePeriodDate[0] + ' ' + '00:00:00').getTime() : '',
        endUsePeriod: this.detailForm.usePeriodDate ? new Date(this.detailForm.usePeriodDate[1] + ' ' + '23:59:59').getTime() : '',
        beginGrantExpiry: this.detailForm.grantExpiryDate ? new Date(this.detailForm.grantExpiryDate[0] + ' ' + '00:00:00').getTime() : '',
        endGrantExpiry: this.detailForm.grantExpiryDate ? new Date(this.detailForm.grantExpiryDate[1] + ' ' + '23:59:59').getTime() : ''
      }
      if (this.addSave) {
        this.$alert('服务商不存在，请重新选择')
      } else {
        Promise.all([rulesOne, rulesTwo]).then(() => {
          this.pageLoading = true
          saveCoupon(params).then(res => {
            if (res) {
              if (Number(res.code) === 1) {
                this.$alert('保存成功').then(() => {
                  this.goBack()
                })
              } else {
                this.$alert('保存失败')
              }
              this.pageLoading = false
            }
          })
        }).catch(() => {
        })
      }
    },
    onClear () {
      this.$confirm('清空后不可恢复，是否继续？', {
        confirmButtonText: '确定',
        showCancelButton: false
      }).then(() => {
        if (this.isAdd) {
          this.couponForm = {
            couponCode: '',
            source: '',
            couponName: '',
            consumer: '',
            distributionMethod: ''
          }
          this.detailForm = {
            businessType: '',
            faceValue: '',
            couponPrefix: '',
            periodType: '1',
            serviceProvidersName: '',
            serviceProvidersCode: '',
            launchQuantity: '',
            description: '',
            grantExpiryDate: '',
            periodDay: '',
            usePeriodDate: '',
            iconUrl: ''
          }
          this.fileList = []
          this.isUpload = false
        } else if (!this.isAdd) {
          if (this.status === '2') {
            this.detailForm.iconUrl = ''
            this.fileList = []
            this.isUpload = false
            this.detailForm.description = ''
          } else if (this.status === '3') {
            return false
          } else {
            if (this.couponForm.source === '1') {
              this.couponForm.couponName = ''
              this.couponForm.consumer = ''
              this.detailForm = {
                businessType: '',
                faceValue: '',
                couponPrefix: '',
                serviceProvidersName: '',
                serviceProvidersCode: '',
                launchQuantity: '',
                description: '',
                grantExpiryDate: '',
                periodDay: '',
                usePeriodDate: '',
                iconUrl: ''
              }
              this.fileList = []
              this.isUpload = false
            } else {
              this.couponForm.couponName = ''
              this.couponForm.consumer = ''
              this.couponForm.distributionMethod = ''
              this.detailForm = {
                businessType: '',
                faceValue: '',
                couponPrefix: '',
                serviceProvidersName: '',
                serviceProvidersCode: '',
                launchQuantity: '',
                description: '',
                grantExpiryDate: '',
                periodDay: '',
                usePeriodDate: '',
                iconUrl: ''
              }
              this.fileList = []
              this.isUpload = false
            }
          }
        }
      })
    },
    // 上传
    onSuccess (res) {
      this.detailForm.iconUrl = res.obj.path
    },
    onError () {
      this.$alert('上传失败，请稍后再试')
    },
    onChange (file, fileList) {
      if (fileList.length !== 0) {
        this.isUpload = true
      } else {
        this.isUpload = false
      }
    },
    handleRemove () {
      this.isUpload = false
    },
    goBack () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  .detail-content-section {
    /deep/ .el-form-item {
      margin-bottom: 22px;
    }
  }
}
/deep/ .el-upload--picture-card {
  width: 88px;
  height: 88px;
  line-height: 88px;
  background: transparent;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 88px;
  height: 88px;
  line-height: 88px;
  background: transparent;
}
/deep/ .el-upload-list__item.is-success .el-upload-list__item-status-label {
  display: none;
}
.hideUpload /deep/ .el-upload {
  display: none; /* 上传按钮隐藏 */
}
/deep/ .el-textarea__inner {
  border-radius: 15px;
}

.el-textarea /deep/ textarea {
  padding-right: 45px;
}

/deep/ .el-textarea .el-input__count {
    height: 20px;
    text-align: center;
    line-height: 20px;
    padding: 0px 4px;
}

/deep/ .el-autocomplete {
  width: 100% ;
}
</style>
